package cn.ekuma.pos.pda.qkorder;


import com.openbravo.bean.erp.Order;
import com.openbravo.bean.erp.OrderLine;
import com.openbravo.data.loader.KeyBuilder;
import cn.ekuma.data.ui.android.BaseBeanListSelecter;
import cn.ekuma.epos.datalogic.local.LocalERPDBHelper;
import cn.ekuma.epos.datalogic.local.erp.dao.FindOrdersInfoDAO;
import cn.ekuma.pos.android.erp.R;
import cn.ekuma.pos.pda.qkorder.OrderManager.PageChangeListener;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import cn.ekuma.android.ui.Navigator;
import cn.ekuma.android.ui.Navigator.NavigatorListener;


public class OrderPanelActivity extends Activity implements PageChangeListener, NavigatorListener {

	public static String ORDER_TO_SHOW="orderToShow";
	
	public static final int MENU_SAVE_TO_lOCAL_DB=Menu.FIRST;

	OrderManager manager;
	OrderLineListAdapter lineAdapter;
	Navigator navigator;
	BaseBeanListSelecter<OrderLine> orderList;
	Order currentOrder;
	FindOrdersInfoDAO localOrderDAO;
	
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order);
		orderList=(BaseBeanListSelecter<OrderLine>) this.findViewById(R.id.orderLineList);
		manager=new OrderManager();
		manager.setPageChangeListener(this);
		navigator=(Navigator) this.findViewById(R.id.navigator);
		navigator.setNavigatorListener(this);
		lineAdapter=new OrderLineListAdapter(this);
		orderList.setAbstractBaseBeanAdapter(lineAdapter);
		Bundle mBundle=getIntent().getExtras();
		currentOrder=(Order) mBundle.getSerializable(ORDER_TO_SHOW);
		manager.setOrder(currentOrder, false);
		
		 LocalERPDBHelper dbHelper=new LocalERPDBHelper(this);
   	     localOrderDAO=new FindOrdersInfoDAO(dbHelper);
	}

	  
	  public boolean onCreateOptionsMenu(Menu menu) {
	    super.onCreateOptionsMenu(menu);
	    menu.add(Menu.NONE, MENU_SAVE_TO_lOCAL_DB, Menu.NONE, R.string.saveToLocalDB).setIcon(android.R.drawable.ic_menu_info_details);
	    return true;
	  }


	  
	  public boolean onOptionsItemSelected(MenuItem item) {
		  switch (item.getItemId()){
	          case MENU_SAVE_TO_lOCAL_DB:
	        	  if(currentOrder!=null){
	        		  if(localOrderDAO.exist(KeyBuilder.getKey(currentOrder.getId())))
	        			  Toast.makeText(this, "当前单据以存在", Toast.LENGTH_SHORT).show();
	        		  else
	        		      localOrderDAO.save(currentOrder);
	        	  }
	        	  break;
		  }
		  return true;
	  }
	
	
	
	
	public void moveFirst() {
		manager.pageFirst();
	}

	
	public void movePrev() {
		manager.pageUp();
		
	}

	
	public void moveNext() {
		manager.pageDown();
		
	}

	
	public void moveEnd() {
		manager.pageEnd();
		
	}

	
	public void moveTo(int posi) {
	}

	
	public void pageChanged(int pageIndex) {
		lineAdapter.clear();
		for(OrderLine l:manager.getLines())
		   lineAdapter.add(l);
		navigator.setCurrentPageIndex(pageIndex);
	}
	
}
